//
//  CourseDetailViewController.m
//  ShowYork
//
//  Created by hxh on 2020/9/2.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "LessonDetailViewController.h"
#import "LessonLeaderViewController.h"
#import "LessonTeacherViewController.h"
#import "ExercisesAnswerResultViewController.h"
#import "ExercisesPageViewController.h"
#import "VideoPlayerViewController.h"
#import "LessonDetailVideoCell.h"
#import "LessonDetaiAfterClassCell.h"
#import "LessonDetailTeacherCell.h"
#import "LessonClassItemCell.h"
#import "LessonTitleHeaderView.h"
#import "LessonDetailModel.h"
#import "LessonPageItemModel.h"
#import "LessonPlanModel.h"

#import "RPAppShareView.h"

@interface LessonDetailViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate,LessonDetaiAfterClassCellDelegate,LessonDetailVideoCellDelegate,LessonClassItemCellDelegate>
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)UIView *navView;
@property (nonatomic,strong)LessonDetailModel *dtlModel;
@property (nonatomic,copy)NSArray *otherArray;
@property (nonatomic,strong)UIButton *backBtn;
@property (nonatomic,strong)UIButton *shareBtn;


@property (nonatomic,strong)UIView *noDataView;
@property (nonatomic,strong)UIImageView *noDataImgView;
@property (nonatomic,strong)UILabel *noDataLb;
@property (nonatomic,strong)UIButton *noDataBackBtn;

@property (nonatomic,assign)BOOL isShowToast;

@property (nonatomic,assign)UIDeviceOrientation oldDeviceOrientation;

@end

@implementation LessonDetailViewController


- (UIStatusBarStyle)preferredStatusBarStyle {
    
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.isHideNavBar = YES;
    
    self.isShowToast = YES;
    
    [self registNote];
    
    if ([RPAppManager isShowNetworkView]) {
        @zf_weakify(self)
        [self showNetworkErrorWithNavTitle:@"课程详情" completeBlock:^{
            @zf_strongify(self)
            [self setUI];
            [self loadNetwork];
        } cancelBlock:^{
            @zf_strongify(self)
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }else{
        [self setUI];
        [self loadNetwork];
    }
   
}

- (void)setUI{
    [self setCollectioView];
    [self setNavView];
    [self setNoDataView];
    [self registNote];
}
- (void)setCollectioView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:[LessonDetailVideoCell class] forCellWithReuseIdentifier:@"LessonDetailVideoCell"];
    [self.collectionView registerClass:[LessonDetailTeacherCell class] forCellWithReuseIdentifier:@"LessonDetailTeacherCell"];
    [self.collectionView registerClass:[LessonClassItemCell class] forCellWithReuseIdentifier:@"LessonClassItemCell"];
    [self.collectionView registerClass:[LessonDetaiAfterClassCell class] forCellWithReuseIdentifier:@"LessonDetaiAfterClassCell"];
    [self.collectionView registerClass:[LessonTitleHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"LessonTitleHeaderView"];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];

    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
    }];
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.cl_height = 138.0f;
    self.collectionView.mj_footer = footer;
    
    [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(GK_STATUSBAR_HEIGHT);
        make.right.equalTo(self.view.mas_right);
        make.left.equalTo(self.view.mas_left);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
}
- (void)setNavView{
    self.navView = [[UIView alloc]init];
    self.navView.backgroundColor = [UIColor whiteColor];
    self.navView.alpha = 0;
    [self.view addSubview:self.navView];
        
    [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(GK_STATUSBAR_HEIGHT);
        make.right.equalTo(self.view.mas_right);
        make.left.equalTo(self.view.mas_left);
        make.height.mas_equalTo(44);
    }];
        
    self.backBtn = [[UIButton alloc]init];
    [self.backBtn setImage:[UIImage imageNamed:@"common_back_normal_tag"] forState:UIControlStateNormal];
    [self.backBtn setImage:[UIImage imageNamed:@"common_back_tag"] forState:UIControlStateSelected];
    [self.backBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backBtn];
        
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.navView).offset(16);
        make.top.bottom.equalTo(self.navView);
    //        make.width.mas_equalTo(50);
    }];
        
    self.shareBtn = [[UIButton alloc]init];
    [self.shareBtn setImage:[UIImage imageNamed:@"home_detail_head_share_tag"] forState:UIControlStateNormal];
    [self.shareBtn setImage:[UIImage imageNamed:@"campus_share_tag"] forState:UIControlStateSelected];
    [self.shareBtn addTarget:self action:@selector(shareMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.shareBtn];
            
    [self.shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.navView).offset(-16);
        make.top.bottom.equalTo(self.navView);
        //        make.width.mas_equalTo(50);
    }];
    
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = [UIColor lightGrayColor];
    [self.navView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.navView);
        make.height.mas_equalTo(0.5);
    }];
    
    
    self.backBtn.hidden = YES;
    self.shareBtn.hidden = YES;

    self.collectionView.mj_footer.hidden = YES;
}
- (void)setNoDataView{
    self.noDataView = [[UIView alloc]init];
    self.noDataView.backgroundColor = [UIColor whiteColor];
    self.noDataView.hidden = YES;
    [self.view addSubview:self.noDataView];
    
    [self.noDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    self.noDataBackBtn = [[UIButton alloc]init];
    [self.noDataBackBtn setImage:[UIImage imageNamed:@"common_back_tag"] forState:UIControlStateNormal];
    [self.noDataBackBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.noDataView addSubview:self.noDataBackBtn];
    
    [self.noDataBackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.noDataView).offset(kNavStatusBarHeight);
        make.size.mas_equalTo(CGSizeMake(44, 44));
        make.left.equalTo(self.noDataView);
    }];
    
    self.noDataImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"course_noData_tag"]];
    [self.noDataView addSubview:self.noDataImgView];
    [self.noDataImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.noDataView);
    }];
    self.noDataLb = [[UILabel alloc]init];
    self.noDataLb.textColor = RGBA(198, 198, 197, 1);
    self.noDataLb.font = font(12);
    self.noDataLb.text = @"课程不存在";
    self.noDataLb.textAlignment = NSTextAlignmentCenter;
    [self.noDataView addSubview:self.noDataLb];
    [self.noDataLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.noDataView);
        make.top.equalTo(self.noDataImgView.mas_bottom).offset(8);
    }];
    
}
- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateAboutQuestionSource:) name:@"updateAboutQuestionSource" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popToRootViewControllerByRemoteMessage) name:@"popToRootViewControllerByRemoteMessage" object:nil];
}

- (void)popToRootViewControllerByRemoteMessage{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 处理通知
- (void)updateAboutQuestionSource:(NSNotification *)note{
    [self loadNetwork];
}
- (void)orientChange:(NSNotification *)notification{
    UIDeviceOrientation  orient = [UIDevice currentDevice].orientation;
    if (orient == UIDeviceOrientationPortrait) {
        [self.collectionView reloadData];
    }
}
#pragma mark - 按钮点击事件
- (void)backMethod{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)shareMethod{
    
    [RPAppShareView showCompleteblock:^(XHShareViewPlatformType platformType) {
        UMSocialPlatformType type = UMSocialPlatformType_UnKnown;
        switch (platformType) {
            case XHShareViewPlatformTypeWeChatSession:
                type = UMSocialPlatformType_WechatSession;
                break;
            case XHShareViewPlatformTypeWeChatMoments:
                type = UMSocialPlatformType_WechatTimeLine;
                break;
            case XHShareViewPlatformTypeQQ:
                type = UMSocialPlatformType_QQ;
                break;
                
            case XHShareViewPlatformTypeQQZone:
                type = UMSocialPlatformType_Qzone;
                break;
            
            case XHShareViewPlatformTypeQQWeibo:
                type = UMSocialPlatformType_Sina;
                break;
            default:
                break;
        }
        if (![[UMSocialManager defaultManager] isInstall:type]) {
            if (type == UMSocialPlatformType_WechatSession || type == UMSocialPlatformType_WechatTimeLine) {
                [WHToast showMessage:@"请先安装微信" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_QQ || type == UMSocialPlatformType_Qzone) {
                [WHToast showMessage:@"请先安装QQ" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_Sina) {
                [WHToast showMessage:@"请先安装微博" duration:2 finishHandler:nil];
            }
            return;
        }

        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
        NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];
        UIImage *shareImage= [UIImage imageNamed:icon];
        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.dtlModel.lesson.title descr:self.dtlModel.lesson.intro.length == 0?@"赋能万千莘莘学子":self.dtlModel.lesson.intro thumImage:shareImage];
        //设置网页地址
        shareObject.webpageUrl = [NSString stringWithFormat:@"%@lesson/lesson/%@",HtmlUrl,self.dtlModel.lesson.id];
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:type messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
                if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                    UMSocialShareResponse *resp = data;
                    //分享结果消息
                    UMSocialLogInfo(@"response message is %@",resp.message);
                    //第三方原始返回的数据
                    UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                }else{
                    UMSocialLogInfo(@"response data is %@",data);
                }
                
                [MobClick event:@"lesson_detail_share"];
                
                [MobClick event:@"lesson_share_total" attributes:@{@"page":@"detail"}];
            }
        }];
    }];
}
#pragma mark - 请求网络
- (void)loadNetwork{
    [self showDataLoadState];
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadDetailSource];
    });
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadOtherLessonSource];
    });

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
       
        [self hideDataLoadLoadState];

        self.dtlModel.lesson.isSeleted =  [[RPAppManager getOwnerPlanIds] containsObject:self.dtlModel.lesson.id];
        
        self.backBtn.hidden = NO;
        
        self.shareBtn.hidden = NO;
        
        self.collectionView.mj_footer.hidden = NO;
        
        [self.collectionView reloadData];
    });

}
- (void)loadDetailSource{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"lessonId"] = self.lessonId;
    param[@"md5"] = [RPAppManager md5StrWithApi:GetH5LessonDetail];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetH5LessonDetail) parames:param success:^(id responseObj) {

        self.dtlModel = [LessonDetailModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        dispatch_semaphore_signal(sema);
    } failure:^(NSError *error) {
        if (error.code == 2) {
            self.noDataView.hidden = NO;
        }
        
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
- (void)loadOtherLessonSource{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = self.lessonId;
    param[@"md5"] = [RPAppManager md5StrWithApi:GetOtherLessons];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetOtherLessons) parames:param success:^(id responseObj) {
        self.otherArray = [LessonPageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        dispatch_semaphore_signal(sema);
    } failure:^(id error) {
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    // 判断偏移量
    // 下拉
    if (scrollView.contentOffset.y <= 0) {
        self.navView.alpha = 0;
        self.backBtn.selected = NO;
        self.shareBtn.selected = NO;
        
        scrollView.contentOffset = CGPointMake(0, 0);
        
    }else{
        CGFloat alpha = scrollView.contentOffset.y * (1/64.0);

        self.navView.alpha = alpha;
        
        if (alpha >= 1) {
            self.backBtn.selected = YES;
            self.shareBtn.selected = YES;
        }
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (self.dtlModel == nil) {
        return 0;
    }
    CGFloat otherCount = self.otherArray.count == 0?0:1;
    if (self.dtlModel.paper == nil) {
        return otherCount+2;
    }else{
        return otherCount+3;
    }
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 1) {
        return 2;
    }
    if (self.dtlModel.paper != nil) {
        if (section == 2) {
            return 1;
        }
        if (section == 3) {
            return MIN(self.otherArray.count, 6);
        }
    }else{
        if (section == 2) {
            return MIN(self.otherArray.count, 6);
        }
    }
    return 1;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        LessonDetailTeacherCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LessonDetailTeacherCell" forIndexPath:indexPath];
        if (indexPath.row == 0) {
            [cell setCourseDetailLeader:self.dtlModel.teacherLeader];
        }else{
            [cell setCourseDetailTeacher:self.dtlModel.teacher];
        }
        return cell;
    }
    if (self.dtlModel.paper != nil) {
        if (indexPath.section == 2) {
            LessonDetaiAfterClassCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LessonDetaiAfterClassCell" forIndexPath:indexPath];
            [cell setModel:self.dtlModel];
            cell.delegate = self;
            return cell;
        }
        if (indexPath.section == 3) {
            LessonClassItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LessonClassItemCell" forIndexPath:indexPath];
            [cell setModel:self.otherArray[indexPath.row]];
            cell.delegate = self;
            return cell;
        }
    }else{
        if (indexPath.section == 2) {
            LessonClassItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LessonClassItemCell" forIndexPath:indexPath];
            [cell setModel:self.otherArray[indexPath.row]];
            cell.delegate = self;
            return cell;
        }
    }
    
    LessonDetailVideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LessonDetailVideoCell" forIndexPath:indexPath];
    [cell setModel:self.dtlModel.lesson];
    cell.delegate = self;
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            [MobClick event:@"lesson_detail_leader_click"];
            LessonLeaderViewController *leaderVC = [[LessonLeaderViewController alloc]init];
            leaderVC.lessonId = self.dtlModel.lesson.id;
            [self.navigationController pushViewController:leaderVC animated:YES];
        }
        if (indexPath.row == 1) {
            [MobClick event:@"lesson_detail_teacher_click"];
            LessonTeacherViewController *teacherVC = [[LessonTeacherViewController alloc]init];
            teacherVC.tearcherId = self.dtlModel.teacher.id;
            [self.navigationController pushViewController:teacherVC animated:YES];
        }

    }
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{

    if (kind == UICollectionElementKindSectionHeader) {
        LessonTitleHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"LessonTitleHeaderView" forIndexPath:indexPath];
        if (self.dtlModel.paper == nil) {
            if (indexPath.section == 1) {
                [header setHeaderTitle:@"老师介绍"];
            }
            if (indexPath.section == 2) {
                [header setHeaderTitle:@"课程推荐"];
            }
        }else{
            if (indexPath.section == 1) {
                [header setHeaderTitle:@"老师介绍"];
            }
            if (indexPath.section == 2) {
                [header setHeaderTitle:@"课后练习"];
            }
            if (indexPath.section == 3) {
                [header setHeaderTitle:@"课程推荐"];
            }
        }
        return header;
    }
    return nil;
}


#pragma mark - UICollectionViewDelegateFlowLayout
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (self.dtlModel.paper == nil) {
        if (section == 2) {
            return UIEdgeInsetsMake(16,16, 16,16);
        }
    }else{
        if (section == 3) {
            return UIEdgeInsetsMake(16,16, 16,16);
        }
    }
    return UIEdgeInsetsZero;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (self.dtlModel.paper == nil) {
        if (section == 2) {
            return 16.0f;
        }
    }else{
        if (section == 3) {
            return 16.0f;
        }
    }
    return 8.0f;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (self.dtlModel.paper == nil) {
        if (section == 2) {
            return 8.0f;
        }
    }else{
        if (section == 3) {
            return 8.0f;
        }
    }
    return 0.01f;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (self.dtlModel.paper == nil) {
        return section == 1?CGSizeMake(kScreenW, 66):CGSizeMake(kScreenW, 50);
    }else{
        if (section == 1 || section == 2 || section == 3) {
            return section == 1?CGSizeMake(kScreenW, 66):CGSizeMake(kScreenW, 50);
        }
    }
    return CGSizeZero;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.dtlModel.paper == nil) {
        if (indexPath.section == 0) {
            return self.dtlModel.lessonSize;
        }
        if (indexPath.section == 1) {
            return  self.dtlModel.teacherSize;
        }
        if (indexPath.section == 2) {
            return self.dtlModel.recommendSize;
        }
    }else{
        if (indexPath.section == 3) {
            return self.dtlModel.recommendSize;
        }
        if (indexPath.section == 0) {
            return self.dtlModel.lessonSize;
        }
        if (indexPath.section == 1) {
            return  self.dtlModel.teacherSize;
        }
        if (indexPath.section == 2) {
            return self.dtlModel.afterClassSize;
        }
    }
    return CGSizeMake(kScreenW, 300);
}

#pragma mark - CourseDetailVideoCellDelegate
- (void)startPlayVideo{
    if (self.dtlModel.lesson.isSeleted) {
        [self pushVideoPlay];
    }else{
        __weak typeof(self)weakSelf = self;
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"将课程加入学习计划，就不怕课程丢失啦～" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
            // 判断有没有哦登录
            if ([RPAppManager isLogin]) {
                // 加入学习不需要提醒
                weakSelf.isShowToast = NO;
                // 默认选中
                weakSelf.dtlModel.lesson.isSeleted = YES;
                // 后执行加入学习计划接口
                [weakSelf addUserPlan];
                // 跳转
                [weakSelf pushVideoPlay];
            }else{
                [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
            }
            [MobClick event:@"lesson_detail_video_ok_click"];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"不用，直接看" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
            [weakSelf pushVideoPlay];
            [MobClick event:@"lesson_detail_video_cancel_click"];
        }];
        [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
        [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
                                //往alertViewController上添加alertAction
        [alertController addAction:confirmAction];
        [alertController addAction:cancelAction];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
    }
}
- (void)pushVideoPlay{
        
    VideoPlayerViewController *playVC = [[VideoPlayerViewController alloc]init];
    self.dtlModel.lesson.isAnswerd = self.dtlModel.isAnswerd;
    playVC.items = @[self.dtlModel.lesson];
    playVC.lessonModel = self.dtlModel;
    NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:playVC];
    [self presentViewController:nav animated:YES completion:nil];
    
    __weak typeof(self)weakSelf = self;
    playVC.updateVideoProgress = ^(CGFloat currentTime, CGFloat totalTime) {
        __strong typeof(weakSelf)strongSelf = weakSelf;
        CGFloat rounded_up2 = currentTime / totalTime;
        int value = (int)(floorf(rounded_up2 * 100 * 100));
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"userId"] = [RPAppManager getCustomerId];
        param[@"lessonId"] = strongSelf.dtlModel.lesson.id;
        param[@"videoPlayedTime"] = @(value);
        param[@"md5"] = [RPAppManager md5StrWithApi:SaveUserVideoLog];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SaveUserVideoLog) parames:param success:^(id responseObj) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateStudyPageListProgress" object:nil];
        } failure:^(id error) {

        }];
        
    };
    playVC.updatePlanStatus = ^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.collectionView reloadData];
        if (strongSelf.updateCourseStatus) {
            strongSelf.updateCourseStatus(strongSelf.dtlModel.lesson.id);
        }
    };
}



- (void)addUserPlan{
    
    [MobClick event:@"lesson_detail_add_plan"];
    
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"lessonId"] = self.dtlModel.lesson.id;
    param[@"md5"] = [RPAppManager md5StrWithApi:AddUserPlanList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AddUserPlanList) parames:param success:^(id responseObj) {
        
        self.dtlModel.lesson.isSeleted = YES;
        
        NSMutableArray *arr = [[RPAppManager getOwnerPlanIds] mutableCopy];
        [arr addObject:self.dtlModel.lesson.id];
        [RPAppManager saveUserPlanIdsWithPlans:arr];
        if (self.isShowToast) {
            [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"已加入学习计划" duration:2 finishHandler:nil];
        }
        
        [self.collectionView reloadData];
        
        if (self.updateCourseStatus) {
            self.updateCourseStatus(self.dtlModel.lesson.id);
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateStudyList" object:nil];
        

        
    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}
#pragma mark - CourseDetaiAfterClassCellDelegate
-(void)didAnswer{
    
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    if (self.dtlModel.lesson.isSeleted || self.dtlModel.isAnswerd) {
        [self nextExerciesePage];
    }else{
        __weak typeof(self)weakSelf = self;
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"将课程加入学习计划，就不怕课程丢失啦～" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
           
            if ([RPAppManager isLogin]) {
                weakSelf.isShowToast = NO;
                [weakSelf addUserPlan];
                [weakSelf nextExerciesePage];
                [MobClick event:@"lesson_detail_answer_ok_click"];
            }else{
                [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":weakSelf.navigationController} completion:nil];
            }
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"不用，直接练" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
            [weakSelf nextExerciesePage];
            [MobClick event:@"lesson_detail_answer_cancel_click"];
        }];
        [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
        [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
                                //往alertViewController上添加alertAction
        [alertController addAction:confirmAction];
        [alertController addAction:cancelAction];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
    }
}

- (void)nextExerciesePage{
    [MobClick event:@"lesson_detail_exercise_click"];
    if (self.dtlModel.isAnswerd) {
        ExercisesAnswerResultViewController *resultVC = [[ExercisesAnswerResultViewController alloc]init];
        resultVC.lessonId = self.dtlModel.lesson.id.stringValue;
        [self.navigationController pushViewController:resultVC animated:YES];
    }else{
        ExercisesPageViewController *dtlVC = [[ExercisesPageViewController alloc]initWithLessonId:self.dtlModel.lesson.id paperId:self.dtlModel.paper.id];
        [self.navigationController pushViewController:dtlVC animated:YES];
    }
}

#pragma mark - CourseClassItemCellDelegate
- (void)addCoursePlanAtCurrentModel:(LessonPageItemModel*)model{
    
    [MobClick event:@"lesson_detail_recommend_add_plan"];
    
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"lessonId"] = model.id;
    param[@"md5"] = [RPAppManager md5StrWithApi:AddUserPlanList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AddUserPlanList) parames:param success:^(id responseObj) {
        
        NSMutableArray *arr = [[RPAppManager getOwnerPlanIds] mutableCopy];
        
        [arr addObject:model.id];
        
        [RPAppManager saveUserPlanIdsWithPlans:arr];
    
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"已加入学习计划" duration:2 finishHandler:nil];
                  
        NSInteger index = [self.otherArray indexOfObject:model];
        
        NSIndexPath *otherIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        
        NSIndexPath *mainIndexPath = [NSIndexPath indexPathForRow:index inSection:3];
        
        [self.collectionView reloadItemsAtIndexPaths:@[otherIndexPath,mainIndexPath]];
        
        if (self.updateCourseStatus) {
            self.updateCourseStatus(model.id);
        }
        
        
    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}
- (void)showCourseDetailWithCurrentModel:(LessonPageItemModel *)model{
    
    [MobClick event:@"lesson_detail_recommend_click"];
    [MobClick event:@"lesson_show_total" attributes:@{@"enter":@"lesson_detail_recommend"}];
    
    LessonDetailViewController *dtlVC = [[LessonDetailViewController alloc]init];
    dtlVC.lessonId = model.id;
    [self.navigationController pushViewController:dtlVC animated:YES];
}

@end
